﻿
Imports System.Threading
Imports lock_t = lock(Of locks.monitorlock)

Public Class countEvent
    Private mre As ManualResetEvent = Nothing
    Private lock As lock_t
    Private i As Int32 = 0

    Public Function isset() As Boolean
        Return mre.WaitOne(0)
    End Function

    Public Function wait(Optional ByVal ms As Int32 = Timeout.Infinite) As Boolean
        If ms < 0 Then
            ms = Timeout.Infinite
        End If
        Dim needWait As Boolean = False
        Dim rtn As Boolean = False
        lock.wait()
        assert(i >= 0)
        If i > 0 Then
            rtn = (i > 1) OrElse mre.Reset()
            i -= 1
            needWait = False
        Else
            needWait = True
        End If
        lock.release()
        If needWait Then
            rtn = mre.WaitOne(ms)
        End If
        Return rtn
    End Function

    Public Function [set]() As Boolean
        Dim rtn As Boolean = False
        lock.wait()
        rtn = (i > 0) OrElse mre.Set()
        i += 1
        lock.release()
        Return rtn
    End Function

    Public Sub New()
        mre = New ManualResetEvent(False)
    End Sub

    Protected Overrides Sub Finalize()
        mre.Close()
        GC.KeepAlive(mre)
        MyBase.Finalize()
    End Sub
End Class
